package day8;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ExceptionDemo {

     //StringIndexOutOfBoundsException 字符串下标越界异常
    @Test
    public void test1() {
        String str = "hello";
        char ch1 = str.charAt(4);
        System.out.println(ch1);
        // java.lang.StringIndexOutOfBoundsException: String index out of range: 5
        char ch2 = str.charAt(5);
        System.out.println(ch2);
    }

    // ArithmeticException 算数异常
    @Test
    public void test2() {
        int i = 3;
        // java.lang.ArithmeticException: / by zero
        System.out.println(i / 0);
    }

    @Test
    public void test3() {
        // Unhandled exception: java.lang.ClassNotFoundException
        // 未雨绸缪
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test4() throws ClassNotFoundException {
        // throws ClassNotFoundException 我自己不去处理这个异常，谁调用我谁处理这个异常
        Class.forName("com.mysql.jdbc.Driver");
    }

    @Test
    public void test5() {
        try {
            //  需要检查的代码（可能会抛出异常，也可能不会抛出异常）
            FileInputStream fileInputStream = new FileInputStream("a.txt");
        } catch (FileNotFoundException e) {
            // 捕获异常后要处理异常
            e.printStackTrace();
        } finally {
            // 一定会被执行的代码（不管异常抛不抛出都会执行）
            System.out.println("finally.....");
        }
    }

    @Test
    public void test6() {
        try {
            fun();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    // throws FileNotFoundException 我自己不去处理这个异常，谁调用我谁处理这个异常
    private void fun() throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream("a.txt");
    }

    // 多重捕获块（多个catch）
    @Test
    public void test15() {
        try {
            Class.forName("");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java211202?useUnicode=true&characterEncoding=UTF-8","root","1234");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Test
    public void test16() {
        try {
            FileInputStream fileInputStream = new FileInputStream("a.txt");
            fileInputStream.read();
            // FileNotFoundException extends IOException
        }  catch (IOException e) {
            e.printStackTrace();
        } /*catch (FileNotFoundException e) {
            // Exception 'java.io.FileNotFoundException' has already been caught
            e.printStackTrace();
        }*/
    }
}

